<template>
  <div class="meeting-task-page">
    <div class="header">
      <a-image width="40" src="/logo.png" />
      <h3 style="margin-left: 10px">会议任务</h3>
    </div>
    <div class="content">
      <a-tabs v-model:active-key="activeTab" @change="tabsChange">
        <template #extra>
          <div style="margin-left: auto">
            <a-input
              v-model="searchKeyword"
              placeholder="请输入搜索关键词"
              :allow-clear="true"
              @input="handleSearchInput"
              @clear="handleSearchClear"
            >
              <template #prefix>
                <IconSearch />
              </template>
            </a-input>
          </div>
        </template>
        <a-tab-pane
          v-for="tab in visibleTabs"
          :key="tab.key"
          :title="tab.title"
        />
      </a-tabs>
      <div class="table-wrapper">
        <a-table
          :columns="columns"
          :data="data"
          :pagination="false"
          :loading="loading"
          class="custom-table"
          :scroll="{ x: 1200 }"
          @row-click="showMeetingDetails"
        />
      </div>
      <div class="pagination-wrapper">
        <a-pagination
          v-if="activeTab === '1'"
          v-model:current="pageAll.current"
          v-model:page-size="pageAll.pageSize"
          :total="pageAll.total"
          :show-total="pageAll.showTotal"
          :show-jumper="pageAll.showJumper"
          :page-size-options="[5, 10, 20, 50]"
          :show-page-size="true"
          @change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        />
        <a-pagination
          v-else
          v-model:current="pageMine.current"
          v-model:page-size="pageMine.pageSize"
          :total="pageMine.total"
          :show-total="pageMine.showTotal"
          :show-jumper="pageMine.showJumper"
          :page-size-options="[5, 10, 20, 50]"
          :show-page-size="true"
          @change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        />
      </div>
    </div>

        <!-- 详情弹窗 -->
    <a-modal
      v-model:visible="isModalVisible"
      title="会议任务详情"
      width="1100px"
      :footer="false"
      :mask-closable="false"
      class="meeting-detail-modal"
    >
      <div v-if="selectedMeeting" class="meeting-detail">
        <!-- 会议基本信息 -->
        <div class="meeting-info-section">
          <h4 class="section-title">会议信息</h4>
          <a-descriptions :column="2" bordered size="medium" :label-style="{ width: '120px' }" :value-style="{ minWidth: '180px' }">
            <a-descriptions-item label="会议号">{{ selectedMeeting.conferenceId }}</a-descriptions-item>
            <a-descriptions-item label="会议状态">
              <a-tag :color="getStateColor(selectedMeeting.conferenceState)">
                {{ getStateText(selectedMeeting.conferenceState) }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="会议主题" :span="2">{{ selectedMeeting.subject }}</a-descriptions-item>
            <a-descriptions-item label="开始时间">{{ selectedMeeting.meetStartTime }}</a-descriptions-item>
            <a-descriptions-item label="结束时间">{{ selectedMeeting.meetEndTime }}</a-descriptions-item>
            <a-descriptions-item label="会议地点" :span="2">{{ selectedMeeting.location }}</a-descriptions-item>
          </a-descriptions>
        </div>

        <!-- 创建人信息 -->
        <div class="creator-info-section">
          <h4 class="section-title">创建人信息</h4>
          <a-descriptions :column="3" bordered size="medium" :label-style="{ width: '80px' }" :value-style="{ minWidth: '120px' }">
            <a-descriptions-item label="创建人">{{ selectedMeeting.createUserName }}</a-descriptions-item>
            <a-descriptions-item label="工号">{{ selectedMeeting.createUserWorkId }}</a-descriptions-item>
            <a-descriptions-item label="部门">{{ selectedMeeting.createUserDept }}</a-descriptions-item>
          </a-descriptions>
        </div>

        <!-- 服务项目详情 -->
        <div class="services-section">
          <h4 class="section-title">{{ activeTab === '2' ? '我的任务详情' : '服务项目详情' }}</h4>
          <div v-if="getTaskList(selectedMeeting).length > 0" class="services-list">
            <div v-for="(service, index) in getTaskList(selectedMeeting)" :key="index" class="service-item">
              <div class="service-header">
                <a-tag color="blue">{{ activeTab === '2' ? '任务' : '服务' }} {{ index + 1 }}</a-tag>
              </div>
              <a-descriptions :column="1" bordered size="medium" class="service-details" :label-style="{ width: '100px' }" :value-style="{ minWidth: '250px' }">
                <a-descriptions-item v-if="activeTab !== '2'" label="执行人">{{ service.handleUser }}</a-descriptions-item>
                <a-descriptions-item v-else label="负责人">{{ selectedMeeting.createUserName }}</a-descriptions-item>
                <a-descriptions-item label="服务项目">{{ service.meetTask }}</a-descriptions-item>
                <a-descriptions-item label="服务内容">{{ service.meetOtherTask }}</a-descriptions-item>
                <a-descriptions-item v-if="service.extraTask" label="其他要求">
                  <div class="extra-task">{{ service.extraTask }}</div>
                </a-descriptions-item>
              </a-descriptions>
            </div>
          </div>
          <a-empty v-else :description="activeTab === '2' ? '暂无任务项目' : '暂无服务项目'" />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, h, onMounted, reactive, ref, watch } from 'vue'
import { Tag, Tooltip } from '@arco-design/web-vue'
import { IconSearch } from '@arco-design/web-vue/es/icon'
import { getMeetingTask, getSearchMyServe, meeetingTaskFuzzySearch, myTaskFuzzySearch } from '@/apis/meet/component'
import has from '@/utils/has'

// 1. 先声明 tabList、visibleTabs、activeTab
const tabList = [
  { key: '1', title: '全部', permission: 'system:service:searchAllServe' },
  { key: '2', title: '我的任务', permission: 'system:service:searchMyServe' }
]
const visibleTabs = computed(() =>
  tabList.filter((tab) => has.hasPerm(tab.permission))
)
const activeTab = ref(visibleTabs.value.length ? visibleTabs.value[0].key : '')

// 搜索相关变量
const searchKeyword = ref('')
const searchTimer = ref<NodeJS.Timeout | null>(null)

// 加载状态
const loading = ref(false)

// 2. 再声明分页参数
const pageAll = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true
})
const pageMine = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true
})

// 3. 声明数据和 columns
const data = ref<any[]>([])
const columns = [
  {
    title: '会议号',
    dataIndex: 'conferenceId',
    width: 130,
    ellipsis: true
  },
  {
    title: '会议主题',
    dataIndex: 'subject',
    class: 'bg-gray subject-col',
    width: 200,
    ellipsis: true,
    render: ({ record }) => {
      const subject = record.subject || ''
      const display = subject.length > 20 ? `${subject.slice(0, 20)}...` : subject
      return h(
        Tooltip,
        { content: subject, position: 'top' },
        { default: () => h('span', display) }
      )
    }
  },
  {
    title: '会议状态',
    dataIndex: 'conferenceState',
    class: 'status-col',
    width: 100,
    render: ({ record }) => {
      const stateMap = {
        0: { text: '预约', color: 'orange' },
        1: { text: '进行中', color: 'green' },
        3: { text: '已结束', color: 'red' }
      }
      const state = stateMap[record.conferenceState] || { text: '未知状态', color: 'default' }
      return h(Tag, { color: state.color }, () => state.text)
    }
  },
  {
    title: '开始时间',
    dataIndex: 'meetStartTime',
    class: 'bg-gray',
    width: 160,
    ellipsis: true,
    render: ({ record }) => {
      return h(
        Tooltip,
        { content: record.meetStartTime, position: 'top' },
        { default: () => h('span', record.meetStartTime) }
      )
    }
  },
  {
    title: '服务项',
    dataIndex: 'services',
    width: 80,
    align: 'center' as const,
    render: ({ record }) => {
      // 根据不同标签页使用不同的数据字段
      const tasks = activeTab.value === '2' ? record.myTasks : record.services
      const serviceCount = tasks?.length || 0
      const color = serviceCount > 0 ? '#165dff' : '#86909c'
      const backgroundColor = serviceCount > 0 ? '#f2f8ff' : '#f7f8fa'

      return h('span', {
        style: {
          display: 'inline-block',
          minWidth: '24px',
          height: '24px',
          lineHeight: '24px',
          borderRadius: '12px',
          backgroundColor,
          color,
          fontSize: '12px',
          fontWeight: '500',
          textAlign: 'center'
        }
      }, serviceCount.toString())
    }
  },
  {
    title: '执行人',
    dataIndex: 'services',
    width: 200,
    ellipsis: true,
    render: ({ record }) => {
      // 个人任务页面显示当前用户，全部任务页面显示具体执行人
      if (activeTab.value === '2') {
        // 个人任务页面：显示当前用户信息
        return h('span', record.createUserName || '当前用户')
      } else {
        // 全部任务页面：显示具体执行人
        const services = record.services || []
        if (services.length === 0) {
          return h('span', { style: { color: '#999' } }, '无执行人')
        }

        const executors = services.map((service) => service.handleUser).filter(Boolean)
        const uniqueExecutors = [...new Set(executors)] // 去重
        const displayText = uniqueExecutors.join('、')

        return h(
          Tooltip,
          { content: displayText, position: 'top' },
          {
            default: () => h('span', displayText)
          }
        )
      }
    }
  }
]

// 4. 声明接口函数
// 内部调用版本（不控制loading状态）
const _getMeetingTaskFc = async () => {
  const res = await getMeetingTask({
    page: pageAll.current,
    size: pageAll.pageSize
  })
  data.value = res.data.list
  pageAll.total = res.data.total
}

const _getSearchMyServeFc = async () => {
  const res = await getSearchMyServe({
    page: pageMine.current,
    size: pageMine.pageSize
  })
  data.value = res.data.list
  pageMine.total = res.data.total
}

// 外部调用版本（控制loading状态）
const getMeetingTaskFc = async () => {
  try {
    loading.value = true
    await _getMeetingTaskFc()
  } finally {
    loading.value = false
  }
}

const getSearchMyServeFc = async () => {
  try {
    loading.value = true
    await _getSearchMyServeFc()
  } finally {
    loading.value = false
  }
}

// 5. 分页事件
const handlePageChange = (newPage: number) => {
  if (activeTab.value === '1') {
    pageAll.current = newPage
    getMeetingTaskFc()
  } else {
    pageMine.current = newPage
    getSearchMyServeFc()
  }
}

const handlePageSizeChange = (newSize: number) => {
  if (activeTab.value === '1') {
    pageAll.pageSize = newSize
    pageAll.current = 1
    getMeetingTaskFc()
  } else {
    pageMine.pageSize = newSize
    pageMine.current = 1
    getSearchMyServeFc()
  }
}

// 执行搜索
const performSearch = async (keyword: string) => {
  try {
    loading.value = true
    if (keyword.trim()) {
      // 有搜索关键词时执行模糊搜索
      if (activeTab.value === '1') {
        // 全部任务搜索
        const res = await meeetingTaskFuzzySearch({
          page: pageAll.current,
          size: pageAll.pageSize,
          keywords: keyword.trim()
        })
        data.value = res.data.list
        pageAll.total = res.data.total
      } else if (activeTab.value === '2') {
        // 个人任务搜索
        const res = await myTaskFuzzySearch({
          page: pageMine.current,
          size: pageMine.pageSize,
          keywords: keyword.trim()
        })
        data.value = res.data.list
        pageMine.total = res.data.total
      }
    } else {
      // 没有搜索关键词时恢复到初始状态
      if (activeTab.value === '1') {
        await _getMeetingTaskFc()
      } else if (activeTab.value === '2') {
        await _getSearchMyServeFc()
      }
    }
  } finally {
    loading.value = false
  }
}

// 搜索输入处理（带防抖动）
const handleSearchInput = () => {
  // 清除之前的定时器
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
  }

  // 设置新的定时器，500ms后执行搜索
  searchTimer.value = setTimeout(() => {
    performSearch(searchKeyword.value)
  }, 500)
}

// 搜索清除处理
const handleSearchClear = () => {
  searchKeyword.value = ''
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
  }
  // 立即恢复到初始状态
  performSearch('')
}

// 兼容旧的搜索方法（如果其他地方还在使用）
const _getMeet = async (value: string) => {
  await performSearch(value)
}

/**
 * 标签页切换事件
 */
const tabsChange = async (key: string | number) => {
  // 清空搜索关键词
  searchKeyword.value = ''
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
  }

  try {
    loading.value = true
    if (key === 1) {
      // 全部
      await _getMeetingTaskFc()
    }
    if (key === 2) {
      // 个人
      await _getSearchMyServeFc()
    }
  } finally {
    loading.value = false
  }
}

// 保证权限变化时activeTab始终指向可见tab
watch(visibleTabs, (tabs) => {
  if (!tabs.find((tab) => tab.key === activeTab.value)) {
    activeTab.value = tabs.length ? tabs[0].key : ''
  }
})

onMounted(async () => {
  try {
    loading.value = true
    if (activeTab.value === '1') {
      await _getMeetingTaskFc()
    } else if (activeTab.value === '2') {
      await _getSearchMyServeFc()
    }
  } finally {
    loading.value = false
  }
})

// 6. 监听 activeTab
watch(activeTab, async (val) => {
  // 清空搜索关键词
  searchKeyword.value = ''
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
  }

  try {
    loading.value = true
    if (val === '1') {
      await _getMeetingTaskFc()
    } else if (val === '2') {
      await _getSearchMyServeFc()
    }
  } finally {
    loading.value = false
  }
})

// 弹窗逻辑
const selectedMeeting = ref<any>(null)
const isModalVisible = ref(false)

const showMeetingDetails = (record) => {
  selectedMeeting.value = record
  isModalVisible.value = true
}

// 状态相关的辅助函数
const getStateText = (state: string | number) => {
  const stateMap = {
    0: '预约',
    1: '进行中',
    3: '已结束'
  }
  return stateMap[state] || '未知状态'
}

const getStateColor = (state: string | number) => {
  const colorMap = {
    0: 'orange',
    1: 'green',
    3: 'red'
  }
  return colorMap[state] || 'default'
}

// 获取任务列表的辅助函数
const getTaskList = (meeting: any) => {
  if (!meeting) return []
  // 个人任务页面使用 myTasks，全部任务页面使用 services
  return activeTab.value === '2' ? (meeting.myTasks || []) : (meeting.services || [])
}
</script>

<style scoped>
.meeting-task-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
}

.header {
  display: flex;
  align-items: center;
  padding: 1rem;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.table-wrapper {
  flex: 1;
  min-height: 0;
  overflow-x: auto;
  margin-top: 10px;
  min-width: 1200px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.custom-table :deep(.arco-table-th) {
  background-color: #f5f5f5 !important;
}

.custom-table :deep(.bg-gray) {
  background-color: #f5f5f5 !important;
}

.custom-table :deep(.arco-table-tr:hover) {
  background-color: #f0f0f0;
  cursor: pointer;
}

.custom-table :deep(.arco-table-cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.custom-table :deep(.subject-col) {
  padding-right: 4px !important;
  padding-left: 4px !important;
}

.custom-table {
  min-width: 1200px;
  overflow-x: auto;
}

/* 弹窗样式 */
.meeting-detail-modal :deep(.arco-modal) {
  width: 1100px !important;
  max-width: 90vw !important;
}

.meeting-detail-modal :deep(.arco-modal-container) {
  width: 1100px !important;
  max-width: 90vw !important;
}

.meeting-detail {
  max-height: 70vh;
  overflow-y: auto;
  width: 100%;
}

.section-title {
  margin: 0 0 12px 0;
  color: #1d2129;
  font-size: 16px;
  font-weight: 600;
  border-left: 4px solid #165dff;
  padding-left: 8px;
}

.meeting-info-section,
.creator-info-section,
.services-section {
  margin-bottom: 24px;
}

.services-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.service-item {
  border: 1px solid #e5e6eb;
  border-radius: 6px;
  padding: 16px;
  background-color: #fafafa;
}

.service-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.service-details {
  margin-top: 8px;
}

.extra-task {
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 1.5;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .table-wrapper {
    min-width: 1100px;
  }

  .custom-table {
    min-width: 1100px;
  }
}
</style>
